<script setup lang="ts">
import type { UploadProps } from 'element-plus'
import { ref, onMounted, reactive } from 'vue'
import { userChangeInfoAPI, bindAccountAPI } from '@/http/userInfo'
import { ElMessage } from 'element-plus'
import { changePasswordAPI } from '@/http/admin'
import useUserStore from '@/store/modules/user'

const useStore = useUserStore()
// 原来的名字
const originalName = ref()
// 原来的性别
const originalSex = ref()
// 原来的邮箱
const originalEmail = ref()
const changePwdDataRef = ref()
const dialogVisible = ref(false)
// 修改密码收集表单数据
const changePwdData = reactive({
  account: localStorage.getItem('account'),
  oldPassword: '',
  newPassword: '',
  twoPassword: '',
})
// 获取用户信息
const userInfoData = () => {
  useStore.userInfo()
  originalName.value = useStore.name
  originalSex.value = useStore.sex
  originalEmail.value = useStore.email
}
// 修改密码
const changePwd = () => {
  dialogVisible.value = true
}
// 提交新修改的密码
const onSubmitNewPwd = async () => {
  await changePwdDataRef.value.validate()
  if (changePwdData.newPassword === changePwdData.twoPassword) {
    const res = await changePasswordAPI(changePwdData)
    if (res.status === 1) return ElMessage.error(`${res.message}`)
    ElMessage.success(`${res.message}`)
    dialogVisible.value = false
  } else {
    ElMessage.error('两次输入的密码不一致')
  }
}
// 表单验证规则
const rules = reactive({
  oldPassword: [
    { required: true, message: '请输入您的旧密码', trigger: 'blur' },
    { min: 6, max: 12, message: '密码长度在6-12位之间', trigger: 'change' },
  ],
  newPassword: [
    { required: true, message: '请输入您的新密码', trigger: 'blur' },
    { min: 6, max: 12, message: '密码长度在6-12位之间', trigger: 'change' },
  ],
  twoPassword: [
    { required: true, message: '请再次输入您的密码', trigger: 'blur' },
    { min: 6, max: 12, message: '密码长度在6-12位之间', trigger: 'change' },
  ],
})
// 修改名字
const changeName = async () => {
  if (useStore.name !== originalName.value) {
    const res = await userChangeInfoAPI({
      id: useStore.id,
      name: useStore.name,
    })
    ElMessage({
      type: res.status === 0 ? 'success' : 'error',
      message: res.status === 0 ? `${res.message}` : '修改失败',
    })
    userInfoData()
  } else {
    setTimeout(() => {
      ElMessage({
        type: 'error',
        message: '名字未发生变化，修改失败！',
      })
    }, 1500)
  }
}
// 修改性别
const changeSex = async () => {
  if (useStore.sex !== originalSex.value) {
    const res = await userChangeInfoAPI({
      id: useStore.id,
      sex: useStore.sex,
    })
    ElMessage({
      type: res.status === 0 ? 'success' : 'error',
      message: res.status === 0 ? `${res.message}` : '修改失败',
    })
    userInfoData()
  } else {
    setTimeout(() => {
      ElMessage({
        type: 'error',
        message: '性别未发生变化，修改失败！',
      })
    }, 1500)
  }
}
// 修改邮箱
const changeEmail = async () => {
  if (useStore.email !== originalEmail.value) {
    const res = await userChangeInfoAPI({
      id: useStore.id,
      email: useStore.email,
    })
    ElMessage({
      type: res.status === 0 ? 'success' : 'error',
      message: res.status === 0 ? `${res.message}` : '修改失败',
    })
    userInfoData()
  } else {
    setTimeout(() => {
      ElMessage({
        type: 'error',
        message: '邮箱未发生变化，修改失败！',
      })
    }, 1500)
  }
}
// 上传头像成功后的处理函数
const handleAvatarSuccess: UploadProps['onSuccess'] = (response) => {
  console.log(response)
  if (response.status == 0) {
    useStore.$patch({
      imageUrl: response.url,
    }),
      (async () => {
        await bindAccountAPI({
          account: useStore.account,
          onlyId: response.onlyId,
          url: response.url,
        })
      })()
    ElMessage.success('更新成功')
  } else {
    ElMessage.error('更新失败！')
  }
}
// 上传头像之前的处理函数
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('头像必须是jpg格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('头像必须小于2MB!')
    return false
  }
  return true
}
// 挂载时获取用户信息
onMounted(() => {
  userInfoData()
})
</script>

<template>
  <el-form label-width="auto" style="max-width: 500px">
    <el-form-item label="用户头像">
      <el-upload
        class="avatar-uploader"
        action="http://127.0.0.1:3000/user/uploadAvatar"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
      >
        <img v-if="useStore.imageUrl" :src="useStore.imageUrl" class="avatar" />
        <img
          src="https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png"
          class="avatar"
          v-else
        />
        <!-- <el-icon v-else class="avatar-uploader-icon">
                    <Plus />
                </el-icon> -->
      </el-upload>
    </el-form-item>
    <el-form-item label="用户账号">
      <el-input v-model="useStore.account" disabled style="max-width: 300px" />
    </el-form-item>
    <el-form-item label="用户密码">
      <el-button type="primary" style="margin: 0" @click="changePwd">
        修改密码
      </el-button>
    </el-form-item>
    <el-form-item label="用户姓名">
      <el-input v-model="useStore.name"></el-input>
      <el-button type="primary" @click="changeName">保存</el-button>
    </el-form-item>
    <el-form-item label="用户性别">
      <el-select v-model="useStore.sex" placeholder="选择性别">
        <el-option label="男" value="男" />
        <el-option label="女" value="女" />
      </el-select>
      <el-button type="primary" @click="changeSex">保存</el-button>
    </el-form-item>
    <el-form-item label="用户身份">
      <el-input v-model="useStore.identity" disabled></el-input>
    </el-form-item>
    <el-form-item label="用户部门">
      <el-input v-model="useStore.department" disabled></el-input>
    </el-form-item>
    <el-form-item label="用户邮箱">
      <el-input v-model="useStore.email"></el-input>
      <el-button type="primary" @click="changeEmail">保存</el-button>
    </el-form-item>
  </el-form>

  <el-dialog v-model="dialogVisible" title="修改密码" width="400">
    <el-form
      :model="changePwdData"
      label-width="auto"
      style="max-width: 600px"
      :rules="rules"
      ref="changePwdDataRef"
    >
      <el-form-item label="原密码" prop="oldPassword">
        <el-input
          v-model="changePwdData.oldPassword"
          type="password"
          placeholder="输入您的密码"
        />
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input
          v-model="changePwdData.newPassword"
          type="password"
          placeholder="输入您的密码"
        />
      </el-form-item>
      <el-form-item label="再次确认密码" prop="twoPassword">
        <el-input
          v-model="changePwdData.twoPassword"
          type="password"
          placeholder="再次输入您的密码"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onSubmitNewPwd">确认修改</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.el-input,
.el-select {
  max-width: 300px;
}

.el-button {
  margin-left: 30px;
}

:deep(.el-form-item__label-wrap) {
  display: flex;
  align-items: center;
}

.avatar-uploader .avatar {
  width: 200px;
  height: 200px;
  display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
